<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px"
    >
      <el-form-item label="应用信息" prop="app_id">
        <el-select
          v-model="queryParams.app_id"
          placeholder="请选择应用信息"
        >
          <el-option
            v-for="item in appOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员名称" prop="customer_name">
        <el-input
          v-model="queryParams.customer_name"
          placeholder="请输入会员名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="精确会员名称" prop="customer_exact_name">
        <el-input
          v-model="queryParams.customer_exact_name"
          placeholder="请输入精确会员名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="customer_phone">
        <el-input
          v-model="queryParams.customer_phone"
          placeholder="请输入手机号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="提现记录状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.customer_withdraw_record_status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="ip状态" prop="ip_status">
        <el-select
          v-model="queryParams.ip_status"
          placeholder="ip状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.customer_ip_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="registerTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="createTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary" icon="el-icon-search" size="mini"
          v-hasPermi="['customer:withdrawRecord:query']" @click="handleQuery"
        >
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="showClose">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
        >关闭
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @sort-change="sortChange">
      <el-table-column sortable="custom" label="记录编号" align="center" key="id" prop="id"/>
      <el-table-column label="会员id" align="center" key="customer_id" prop="customer_id"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="openSelectRegisterIpUser(scope.row)"
            v-hasPermi="['customer:user:query']"
          >稽查注册IP
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="transfer(scope.row)"
            v-if="scope.row.status == 1"
            v-hasPermi="['customer:withdrawRecord:transfer','agent:withdraw:transfer']"
          >审核通过
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="transfer2(scope.row)"
            v-if="scope.row.status == 1"
            v-hasPermi="['customer:withdrawRecord:transfer','agent:withdraw:transfer']"
          >线下出款
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="fail(scope.row)"
            v-if="scope.row.status == 1"
            v-hasPermi="['customer:withdrawRecord:fail','agent:withdraw:transfer']"
          >申请驳回
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="会员名称" align="center" key="name" prop="name"
                       :show-overflow-tooltip="true" width="160"
      >
        <template slot-scope="scope">
          <router-link :to="'/customer/record/index/' + queryParams.app_id + '/name/' + scope.row.name"
                       class="link-type">
            <el-button size="mini" type="text" icon="el-icon-search">操作</el-button>
          </router-link>
          <span @click="queryExactName(scope.row.name)">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会员手机号" align="center" key="phone" prop="phone"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="一级代理" align="center" key="first_agent_name" prop="first_agent_name"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="注册IP" align="center" key="register_ip" prop="register_ip" width="160"/>
      <el-table-column label="注册时间" align="center" key="register_time" prop="register_time" width="160"/>
      <el-table-column label="充提差" align="center" key="total_deposit_withdraw_differ"
                       prop="total_deposit_withdraw_differ" width="160"/>
      <el-table-column sortable="custom" label="金额" align="center" key="amount" prop="amount"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="ip状态" width="80" prop="ip_status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_ip_status" :value="scope.row.ip_status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" key="create_time" prop="create_time" width="160"/>
      <el-table-column label="网络" align="center" prop="network">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wallet_network" :value="scope.row.network"/>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_withdraw_record_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" key="order_no" prop="order_no"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="交易hash" align="center" key="trade_hash" prop="trade_hash"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="收款地址" align="center" key="income_address" prop="income_address"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="手续费" align="center" key="fee" prop="fee"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="备注" align="center" key="remark" prop="remark"
                       :show-overflow-tooltip="true" width="160"
      />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />

    <el-dialog :title="transferTitle" :visible.sync="transferOpen" width="600px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="transferForm" :model="transferForm" :rules="rules" label-width="80px">
        <el-form-item label="金额计算">
          <span style="color: red">提现金额：{{ transferObj.amount }}</span>
          <br>
          <span style="color: red" v-if="transferObj.fee!== undefined">手续费：{{ transferObj.fee }}</span>
          <br>
          <span style="color: red">实际提现金额：{{ transferObj.transfer_amount }}</span>
        </el-form-item>
        <el-form-item label="支付钱包" prop="tenant_wallet_id">
          <el-select
            v-model="transferForm.tenant_wallet_id"
            placeholder="请选择支付钱包"
            style="width:100%"
          >
            <el-option
              v-for="item in payOptions"
              :key="item.id"
              :label="item.address"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="验证码" prop="google_code">
          <el-input v-model="transferForm.google_code" placeholder="请输入验证码" maxlength="30"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTransferForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="transfer2Title" :visible.sync="transfer2Open" width="600px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="transfer2Form" :model="transfer2Form" :rules="rules" label-width="80px">
        <el-form-item label="金额计算">
          <span style="color: red">提现金额：{{ transfer2Obj.amount }}</span>
          <br>
          <span style="color: red" v-if="transferObj.fee!== undefined">手续费：{{ transfer2Obj.fee }}</span>
          <br>
          <span style="color: red">实际提现金额：{{ transfer2Obj.transfer_amount }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTransfer2Form">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="failTitle" :visible.sync="failOpen" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="failForm" :model="failForm" :rules="rules" label-width="80px">
        <el-form-item label="备注信息" prop="remark">
          <el-input type="textarea" v-model="failForm.remark" placeholder="请输入备注信息" maxlength="30"/>
        </el-form-item>
        <el-form-item label="验证码" prop="google_code">
          <el-input v-model="failForm.google_code" placeholder="请输入验证码" maxlength="30"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFailForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <select-register-ip-customer ref="select"
                                 :app_id="queryParams.app_id"
                                 @ok="handleQuery"
    />
  </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {getGroupApp} from "@/api/metadata/app";
import {
  failCustomerWithdrawRecord,
  listCustomerWithdrawRecord,
  transfer2CustomerWithdrawRecord,
  transferCustomerWithdrawRecord
} from "@/api/customer/customerWithdrawRecord";
import {getPayList} from "@/api/tenant/tenantWallet";
import selectRegisterIpCustomer from "@/views/customer/user/selectRegisterIpCustomer";

export default {
  name: 'CustomerWithdrawRecord',
  computed: {},
  dicts: ['customer_withdraw_record_status', 'wallet_network', 'customer_ip_status'],
  components: {selectRegisterIpCustomer},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: null,
      // 弹出层标题
      title: '',
      // 弹出层标题
      transferTitle: '',
      transfer2Title: '',
      failTitle: '',
      // 是否显示弹出层
      transferOpen: false,
      transfer2Open: false,
      failOpen: false,
      appOptions: [],
      payOptions: [],
      // 日期范围
      registerTimeRange: [],
      createTimeRange: [],
      // 表单参数
      transferForm: {},
      transfer2Form: {},
      failForm: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        customer_id: undefined,
        app_id: undefined,
        customer_name: undefined,
        customer_exact_name: undefined,
        customer_phone: undefined,
        customer_email: undefined,
        status: undefined,
        sort_list: [],
      },
      // 表单校验
      rules: {
        google_code: [
          {required: true, message: '验证码不能为空', trigger: 'blur'}
        ],
        tenant_wallet_id: [
          {required: true, message: '支付地址不能为空', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '备注信息不能为空', trigger: 'blur'}
        ],
      },
      transferObj: {
        amount: undefined,
        fee: undefined,
        transfer_amount: undefined,
      },
      transfer2Obj: {
        amount: undefined,
        fee: undefined,
        transfer_amount: undefined,
      },
      showClose: false,
    }
  },
  created() {
    const exactName = this.$route.params && this.$route.params.exactName;
    if (exactName) {
      this.queryParams.customer_exact_name = exactName
      this.showClose = true
    }
    // 默认id排序
    this.queryParams.sort_list = [{sort_by: 'id', sort_type: 2}]
    const appId = this.$route.params && this.$route.params.appId;
    this.getGroupApp(appId)
  },
  methods: {
    sortChange(column) {
      if (column) {
        if (column.order === 'ascending') {
          this.queryParams.sort_list = [{sort_by: column.prop, sort_type: 1}]
        } else if (column.order === 'descending') {
          this.queryParams.sort_list = [{sort_by: column.prop, sort_type: 2}]
        }
        this.getList()
      }
    },
    getList() {
      this.loading = true
      listCustomerWithdrawRecord(
        this.addDateRange(
          this.addDateRange(this.queryParams, this.registerTimeRange, '_register_time'),
          this.createTimeRange, '_create_time'
        )
      ).then(response => {
          this.dataList = response.data
          this.total = response.total
          this.loading = false
        }
      )
    },
    getGroupApp(appId) {
      getGroupApp().then(response => {
        this.queryParams.type = 1
        this.appOptions = response.data
        if (appId) {
          this.queryParams.app_id = parseInt(appId)
        } else {
          this.queryParams.app_id = response.data[0].id
        }
        this.getList()
      })
    },
    getPayList(appId, network) {
      getPayList(appId, network).then(response => {
        this.payOptions = response.data
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 取消按钮
    cancel() {
      this.transferOpen = false
      this.transfer2Open = false
      this.failOpen = false
      this.transferReset()
      this.transfer2Reset()
      this.failReset()
      this.getList()
    },
    // 表单重置
    transferReset() {
      this.transferForm = {
        id: 1,
        tenant_wallet_id: undefined,
        google_code: undefined,
      }
      this.resetForm('transferForm')
    },
    // 表单重置
    transfer2Reset() {
      this.transfer2Form = {
        id: 1,
        tenant_wallet_id: undefined,
        google_code: undefined,
      }
      this.resetForm('transfer2Form')
    },
    // 表单重置
    failReset() {
      this.failForm = {
        id: 1,
        remark: undefined,
        google_code: undefined,
      }
      this.resetForm('failForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.registerTimeRange = []
      this.createTimeRange = []
      let appId = this.queryParams.app_id
      this.resetForm('queryForm')
      this.queryParams.app_id = appId
      this.handleQuery()
    },
    transfer(row) {
      this.transferReset()
      this.getPayList(this.queryParams.app_id, row.network)
      const id = row.id || this.ids
      this.transferObj.amount = row.amount
      this.transferObj.fee = row.fee
      if (this.transferObj.fee != undefined) {
        this.transferObj.transfer_amount = Number(this.transferObj.amount) - Number(this.transferObj.fee)
      } else {
        this.transferObj.transfer_amount = this.transferObj.amount
      }
      this.transferForm.id = id
      this.transferOpen = true
      this.transferTitle = '审核通过，自动转账'
    },
    transfer2(row) {
      this.transfer2Reset()
      const id = row.id || this.ids
      this.transfer2Obj.amount = row.amount
      this.transfer2Obj.fee = row.fee
      if (this.transfer2Obj.fee != undefined) {
        this.transfer2Obj.transfer_amount = Number(this.transfer2Obj.amount) - Number(this.transfer2Obj.fee)
      } else {
        this.transfer2Obj.transfer_amount = this.transfer2Obj.amount
      }
      this.transfer2Form.id = id
      this.transfer2Open = true
      this.transfer2Title = '审核通过，自动转账'
    },
    fail(row) {
      this.failReset()
      const id = row.id || this.ids
      this.failForm.id = id
      this.failOpen = true
      this.failTitle = '申请驳回'
    },
    /** 提交按钮 */
    submitTransferForm: function () {
      this.$refs['transferForm'].validate(valid => {
        if (valid) {
          let step = async () => {
            transferCustomerWithdrawRecord(this.transferForm).then(response => {
              this.$modal.msgSuccess('审核成功')
              this.transferOpen = false
              this.getList()
            })
          }
          step()
        }
      })
    },
    /** 提交按钮 */
    submitTransfer2Form: function () {
      this.$refs['transfer2Form'].validate(valid => {
        if (valid) {
          let step = async () => {
            transfer2CustomerWithdrawRecord(this.transfer2Form).then(response => {
              this.$modal.msgSuccess('审核成功')
              this.transfer2Open = false
              this.getList()
            })
          }
          step()
        }
      })
    },
    /** 提交按钮 */
    submitFailForm: function () {
      this.$refs['failForm'].validate(valid => {
        if (valid) {
          let step = async () => {
            failCustomerWithdrawRecord(this.failForm).then(response => {
              this.$modal.msgSuccess('驳回成功')
              this.failOpen = false
              this.getList()
            })
          }
          step()
        }
      })
    },
    /** 打开ip一样的用户表弹窗 */
    openSelectRegisterIpUser(row) {
      this.$refs.select.show(row.register_ip);
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = {path: "/customer/customerUser"};
      this.$tab.closeOpenPage(obj);
    },
    /** 精准查询用户名 */
    queryExactName(name) {
      this.queryParams.customer_exact_name = name;
      this.getList()
    },
  }
}
</script>
